package cn.ljy.mes.service.impl;

import cn.ljy.authority.service.impl.IBaseService;
import cn.ljy.common.exception.model.MyWebException;
import cn.ljy.mes.dao.mapper.WmsMaterialInventoryDetailMapper;
import cn.ljy.mes.dao.mapper.WmsMaterialInventoryMapper;
import cn.ljy.mes.model.WmsMaterialInventory;
import cn.ljy.mes.model.query.WmsMaterialInventoryDetailQuery;
import cn.ljy.mes.model.query.WmsMaterialInventoryQuery;
import cn.ljy.mes.service.WmsMaterialInventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;

@Service
//@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor= MyRollBackException.class)
@Validated//表示开启sprint的校检框架，会自动扫描方法里的@Valid（@Valid注解一般写在接口即可）
@Slf4j
public class IWmsMaterialInventoryService extends IBaseService<WmsMaterialInventory, WmsMaterialInventoryQuery> implements WmsMaterialInventoryService {
    @Autowired
    private WmsMaterialInventoryMapper mapper;
    @Autowired
    private WmsMaterialInventoryDetailMapper materialInventoryDetailMapper;

    @Override
    protected void beforeSave(WmsMaterialInventory wmsMaterialInventory) {
        if(wmsMaterialInventory.getMaterial().getId()==null){
            throw new MyWebException("验证失败：必须选择物料");
        }
        //查询是否有相同的物料
        WmsMaterialInventoryQuery query=new WmsMaterialInventoryQuery();
        query.setMaterial(wmsMaterialInventory.getMaterial());
        if(mapper.count(query)>0){
            throw new MyWebException("验证失败：该物料的库存已经建立，无法重复创建");
        }
    }

    @Override
    protected void beforeSaveOrUpdate(WmsMaterialInventory wmsMaterialInventory) {
        if(wmsMaterialInventory.getInventoryLimit()!=null&&wmsMaterialInventory.getInventoryLower()!=null){
            if(wmsMaterialInventory.getInventoryLimit()<wmsMaterialInventory.getInventoryLower()){
                throw new MyWebException("验证失败：库存上限必须大于库存下限");
            }
        }
    }

    @Override
    public void afterFindAll(List<WmsMaterialInventory> list) {
        for(WmsMaterialInventory wmsMaterialInventory:list){
            //添加相关关联属性
            //获取详细库存信息
            WmsMaterialInventoryDetailQuery inventoryDetailQuery=new WmsMaterialInventoryDetailQuery();
            inventoryDetailQuery.setMaterialInventory(wmsMaterialInventory);
            wmsMaterialInventory.setMaterialInventoryDetails(materialInventoryDetailMapper.findAll(inventoryDetailQuery));
            //
        }
    }

}
